/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * frmAddUser.java
 *
 * Created on May 22, 2011, 5:16:33 AM
 */

package Admin;

import Account.SizeMonition;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Types;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

/**
 *
 * @author BachDEV
 */
public class frmAddUser extends javax.swing.JFrame {

    private String username = "";
    private String password = "";
    private String fullname = "";
    private int type = 0;
    private boolean status = true;
    private boolean flag = true;
    private String message = "";
    frmAdminCenter admin;
    public static int x;
    public static int y;

    /** Creates new form frmAddUser */
    public frmAddUser(frmAdminCenter admin) {
        this.admin = admin;
         try{
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        }catch(InstantiationException ex){
            ex.printStackTrace();
        }catch(UnsupportedLookAndFeelException ex){
            ex.printStackTrace();
        }catch(ClassNotFoundException ex){
            ex.printStackTrace();
        }catch(IllegalAccessException ex){
            ex.printStackTrace();
        }
        initComponents();
        Dimension ds = Toolkit.getDefaultToolkit().getScreenSize();
            x = this.getWidth();
            y = this.getHeight();
            this.setLocation((ds.width - this.getWidth()) / 2, (ds.height - this.getHeight()) / 2);
    }

    public void motion() {
        this.setSize(0, 0);
        new Thread(new SizeMonition(this, x, y)).start();
    }
    /////////////////////////////////////////////////////////////////////////
    public void checkField() throws Exception {
        try {
            flag = true;
            message = "";
            if (txtUsername.getText().trim().equals("")) {
                message += "The username cannot be blank!\n";
                flag = false;
            } else {
                if (txtUsername.getText().trim().contains(" ")) {
                    message += "The username cannot contain space character!\n";
                    flag = false;
                } else {
                    if (checkExistUsername(txtUsername.getText())) {
                        message += "This name is existed, try again!\n";
                        flag = false;
                    } else {
                        username = txtUsername.getText().trim();
                    }
                }
            }
            if (pwdPassword.getText().trim().equals("")) {
                message += "The password cannot be blank!\n";
                flag = false;
            } else {
                if (pwdPassword.getText().trim().length() < 4) {
                    message += "Length of password cannot less than 4!\n";
                    flag = false;
                } else {
                    password = pwdPassword.getText().trim();
                }
            }
            if (txtFullName.getText().trim().equals("")) {
                message += "The fullname cannot be blank!\n";
                flag = false;
            } else {
                fullname = txtFullName.getText().trim();
            }
        } catch (Exception ex) {
            throw ex;
        }
    }

    public boolean checkExistUsername(String name) throws Exception {
        Connection connect = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        String sql = "Select * from Users where userName = ?";
        try {
            connect = Connections.DBConnection.getConnection("eProject", "sa", "123");
            stmt = connect.prepareStatement(sql);
            stmt.setString(1, name);
            rs = stmt.executeQuery();
            if (rs.next()) {
                return true;
            } else {
                return false;
            }
        } catch (Exception ex) {
            throw ex;
        } finally {
            try {
                Connections.DBConnection.closeConnection(connect, stmt, rs);
            } catch (Exception ex) {
                throw ex;
            }
        }
    }
    //////////////////////////////////////////////////////////////////////////
     public void saveDatabase(String username, String password, int type, String fullname, boolean status) throws Exception {
        Connection connect = null;
        PreparedStatement stmt = null;
        String sql = "Insert Users values(?,?,?,?,?)";
        try {
            connect = Connections.DBConnection.getConnection("eProject", "sa", "123");
            stmt = connect.prepareStatement(sql);
            stmt.setObject(1, username, Types.VARCHAR);
            stmt.setObject(2, password, Types.VARCHAR);
            stmt.setInt(3, type);
            stmt.setObject(4, fullname, Types.VARCHAR);
            stmt.setBoolean(5, status);
            stmt.executeUpdate();
            JOptionPane.showMessageDialog(this, "Insert successfull!");
            dispose();
            admin.columnUser = admin.getColumn(1);
            admin.listUser = admin.getData(1);
            admin.tblUser = new JTable(admin.listUser, admin.columnUser);

            admin.scrUser.setViewportView(admin.tblUser);
            admin.jTableMouseClicked();
        } catch (Exception ex) {
            throw ex;
        } finally {
            try {
                Connections.DBConnection.closeConnection(connect, stmt, null);
            } catch (Exception ex) {
                throw ex;
            }
        }

    }
     ///////////////////////////////////////////////////////////////////////

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        txtFullName = new javax.swing.JTextField();
        btnCancel = new javax.swing.JButton();
        btnReset = new javax.swing.JButton();
        btnSave = new javax.swing.JButton();
        cbStatus = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        cbType = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        txtUsername = new javax.swing.JTextField();
        pwdPassword = new javax.swing.JPasswordField();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Add new user");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Add new user"));

        jLabel1.setText("Username");

        jLabel6.setText("Full Name");

        btnCancel.setText("Cancel");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        btnReset.setText("Reset");
        btnReset.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnResetActionPerformed(evt);
            }
        });

        btnSave.setText("Save");
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });

        cbStatus.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Enable", "Disable" }));

        jLabel4.setText("Status");

        cbType.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Admin", "Dispatch", "Order Management Department", "Account Department ", "Call Center", "Technical Support" }));

        jLabel3.setText("Type");

        jLabel2.setText("Password");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(17, 17, 17)
                        .addComponent(btnSave, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnReset, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel6)
                            .addComponent(jLabel4)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addGap(20, 20, 20)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(cbStatus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(cbType, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(txtFullName, javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(pwdPassword, javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(txtUsername, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addContainerGap(55, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel2)
                        .addGap(11, 11, 11))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(txtUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(pwdPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtFullName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel6))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(cbType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(cbStatus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel4)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(32, 32, 32)
                        .addComponent(jLabel3)))
                .addGap(26, 26, 26)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnSave)
                    .addComponent(btnReset)
                    .addComponent(btnCancel))
                .addContainerGap(28, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(19, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        // TODO add your handling code here:
        dispose();
        admin.setEnabled(true);
        admin.setAlwaysOnTop(true);
}//GEN-LAST:event_btnCancelActionPerformed

    private void btnResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnResetActionPerformed
        // TODO add your handling code here:
        txtUsername.setText("");
        pwdPassword.setText("");
        txtFullName.setText("");
        cbType.setSelectedIndex(0);
        cbStatus.setSelectedIndex(0);
}//GEN-LAST:event_btnResetActionPerformed

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
        // TODO add your handling code here:
        try {
            checkField();
            if (!flag) {
                JOptionPane.showMessageDialog(this, message);
            } else {
                type = cbType.getSelectedIndex() + 1;
                switch (cbStatus.getSelectedIndex()) {
                    case 0:
                        status = true;
                        break;
                    case 1:
                        status = false;
                        break;
                }
                saveDatabase(username, password, type, fullname, status);

            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
}//GEN-LAST:event_btnSaveActionPerformed

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        // TODO add your handling code here:
        admin.setEnabled(true);
        admin.setAlwaysOnTop(true);
    }//GEN-LAST:event_formWindowClosed


    /**
    * @param args the command line arguments
    */
   

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnReset;
    private javax.swing.JButton btnSave;
    private javax.swing.JComboBox cbStatus;
    private javax.swing.JComboBox cbType;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPasswordField pwdPassword;
    private javax.swing.JTextField txtFullName;
    private javax.swing.JTextField txtUsername;
    // End of variables declaration//GEN-END:variables

}
